from django.contrib.auth.hashers import make_password
from django.shortcuts import render
from rest_framework.generics import CreateAPIView, ListAPIView
# 导入GeetestLib
from rest_framework_jwt.settings import api_settings
from luffyapi.libs.geetest import GeetestLib
# 导入Response
from rest_framework.response import Response
from .utils import get_user_by_account
from rest_framework import status as http_status
# 用户相关
from rest_framework.views import APIView
from .models import User
from .serializers import UserModelSerializer, GetUserModelSerializer

pc_geetest_id = "5e876edb2bda195c265416b70e7389a7"
pc_geetest_key = "c1f0f6f5958507924d187db31cd136e5"
# Create your views here.
class CaptchaAPIView(APIView):
    """验证码视图类"""
    status = False
    user_id = 0
    def get(self, request):
        """获取验证码"""
        username = request.query_params.get("username")
        user = get_user_by_account(username)
        if user is None:
            return Response({"message":"对不起，用户不存在！"},status=http_status.HTTP_400_BAD_REQUEST)
        self.user_id = user.id
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        self.status = gt.pre_process(self.user_id)
        # session ,cookie 全部注释掉
        # request.session[gt.GT_STATUS_SESSION_KEY] = status
        # request.session["user_id"] = user_id
        response_str = gt.get_response_str()
        return Response(response_str)

    def post(self, request):
        """验证码的校验"""
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        # status = request.session[gt.GT_STATUS_SESSION_KEY]
        # user_id = request.session["user_id"]
        if self.status:
            result = gt.success_validate(challenge, validate, seccode, self.user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        return Response(result)

class Login2APIView(CreateAPIView):
    """短信验证码(登录)"""
    # 1. 获取用户信息
    # 2.检验用户
    # 3.验证验证码

    queryset = User.objects.all()
    serializer_class = GetUserModelSerializer

class UserAPIView(CreateAPIView):
    """用户信息视图(注册)"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer
from rest_framework.generics import ListAPIView
from order.models import Order
from .serializers import UserOrderModelSerializer
from rest_framework.permissions import IsAuthenticated
class UserOrderAPIView(ListAPIView):
    serializer_class = UserOrderModelSerializer
    permission_classes = [IsAuthenticated]
    def get_queryset(self):
        return Order.objects.filter(user_id=self.request.user.id)

from rest_framework import  status
class MobileAPIView(APIView):
    def get(self, request, mobile):
        ret = get_user_by_account(mobile)
        if ret is not None:
            return Response({"message": "手机号已经被注册过!"}, status.HTTP_400_BAD_REQUEST)
        return Response({"message":"ok"})


import random
from django_redis import get_redis_connection
from luffyapi.settings import constants
from luffyapi.libs.yuntongxun.sms import CCP

import logging
log = logging.getLogger("django")

class SMSAPIView(APIView):
    def get(self,request,mobile):
        """短信发送"""

        # 1. 判断手机号码是否在60秒内曾经发送过短信
        redis_conn = get_redis_connection("sms_code")
        ret = redis_conn.get("mobile_%s" % mobile)
        if ret is not None:
            return Response({"message":"对不起，60秒内已经发送过短信，请耐心等待"},status=status.HTTP_400_BAD_REQUEST)

        # 2. 生成短信验证码
        sms_code = "%06d" % random.randint(1, 999999)

        # 3. 保存短信验证码到redis
        # 创建管道对象
        pipe = redis_conn.pipeline()
        # 开启事务[无法管理数据库的读取数据操作]
        pipe.multi()
        # 把事务中要完成的所有操作,写入到管道中

        redis_conn.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
        redis_conn.setex("mobile_%s" % mobile, constants.SMS_INTERVAL_TIME,"_")

        # 执行事务
        pipe.execute()
        # 4. 调用短信sdk，发送短信
        try:
            # from mycelery.sms.tasks import send_sms
            # send_sms.delay(mobile, sms_code)
            ccp = CCP()
            ret = ccp.send_template_sms(mobile, [sms_code, constants.SMS_EXPIRE_TIME//60], constants.SMS_TEMPLATE_ID)
            if not ret:
                log.error("用户注册短信发送失败！手机号：%s" % mobile)
                return Response({"message":"发送短信失败！"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except:
            return Response({"message":"发送短信失败！"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 5. 响应发送短信的结果
        return Response({"message":"发送短信成功！"})


# 导入邮箱
from django.core.mail import send_mail
from luffyapi.settings.dev import EMAIL_PROM
class EmailAPIView(APIView):
    def get(self, request):
        # 判断用户是否存在
        username = request.query_params.get("username")
        ret = User.objects.filter(username=username).first()

        print(ret)
        if ret is not None:
            emailaddress = ret.email
            nametemp = ret.username
            idtemp = ret.id
            mobiletemp = ret.mobile
            print(emailaddress, nametemp, idtemp)

            # 生成随机密码
            pwd = "%06d" % random.randint(1, 999999)
            print(pwd)
            pwdtemp = make_password(pwd)
            print(pwdtemp)

            # 删除旧的密码把新密码放在数据库中
            object = User.objects.filter(mobile=mobiletemp)
            object.update(id=idtemp, username=nametemp, password=pwdtemp,email=emailaddress,mobile=mobiletemp)
            # User.objects.filter(username).update(id=idtemp, username=nametemp,password=pwdtemp, email=emailaddress)
        subject = "密码修改成功:"
        message = "尊敬的用户,您的新密码为%s" % pwd
        sender = EMAIL_PROM
        receiver = [emailaddress]
        send_mail(subject, message, sender,receiver)